﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Web.Http;
using JWT.Algorithms;
using JWT.Serializers;
using JWT;
using Project.API.Models;
using Project.BLL;
using Project.Model;
using Swashbuckle.Swagger;

namespace Project.API.Controllers
{
    //[ApiAuthorize]
    public class CustomerController : ApiController
    {
        Entities model=new Entities();
        // GET: api/Customer
        public ResultPageList<customerDto> Get(int page, int limit, string name = "")
        {
            int count = 0;
            var list = new customerBll().GetCustomerByPage(name, page, limit, out count);

            var data = from u in list
                       select new customerDto
                       {
                           CId = u.CId,
                           nickname = u.nickname,
                           mobilePhone = u.mobilePhone,
                           loginPwd = u.loginPwd,
                           gender = u.gender,
                           birthday = u.birthday,
                           address = u.address,
                       };

            ResultPageList<customerDto> result = new ResultPageList<customerDto>();
            result.code = 0;
            result.msg = "ok";
            result.count = count;
            result.data = data.ToList();

            return result;
        }

        //手机端登录
        [HttpGet]
        [Route("api/Customer/Login")]
        public dynamic Login(string phone, string loginpwd)
        {
            //密钥
            //string JwtKey = ConfigurationManager.AppSettings["JwtKey"];
            ////过期周期
            //string JwtExp = ConfigurationManager.AppSettings["JwtExp"];

            ////过期时间
            //var exp = string.IsNullOrWhiteSpace(JwtExp) ? 30 : int.Parse(JwtExp);


            dynamic data = new ExpandoObject();

            customer user = ValidateUser(phone, loginpwd);
            if (user != null)
            {
                try
                {
                    ////加密方式
                    //IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                    ////序列化方式
                    //IJsonSerializer serializer = new JsonNetSerializer();
                    ////编码方式
                    //IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    ////声明Jwt
                    //IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

                    //生成Token
                    //var token = encoder.Encode(info, JwtKey);
                    //info.Token = token;
                    customer info = new customer
                    {
                        CId=user.CId,
                        nickname = user.nickname,
                        mobilePhone = user.mobilePhone,
                        loginPwd = user.loginPwd,
                        gender = user.gender,
                        birthday = user.birthday,
                        address= user.address,
                    };
                    data.msg = "登录成功";
                    data.data = info;
                    data.code = 1;
                }
                catch (Exception ex)
                {
                    data.msg = ex.Message;
                    data.code = -2;
                }
            }
            else
            {
                data.code = -1;
                data.msg = "账户或者密码错误！";
            }
            return data;

        }

        //校验用户名密码（正式环境中应该是数据库校验）
        private customer ValidateUser(string phone, string loginpwd)
        {
            customerBll bll = new customerBll();

            loginpwd = MD5Helper.Md5(loginpwd, "X2");

            customer user = bll.Query().Where(u => u.mobilePhone == phone && u.loginPwd == loginpwd).FirstOrDefault();

            return user;
        }
        // GET: api/Customer/5
        public string Get(int id)
        {
            return "value";
        }


        [Route("api/Customer/Shen")]
        public ResultData<List<area>> GetShen()
        {
            var data = model.area.Where(a => a.level == 1);

            ResultData<List<area>> result = new ResultData<List<area>>();
            result.code = data.Count();
            result.msg = "ok";
            result.data = data.ToList();

            return result;
        }

        [Route("api/Customer/ShiQu")]
        public ResultData<List<area>> GetShiQu(string name)
        {
            int id = model.area.Where(a => a.district == name).FirstOrDefault().aid;

            var data = model.area.Where(a => a.pid == id);

            ResultData<List<area>> result = new ResultData<List<area>>();
            result.code = data.Count();
            result.msg = "ok";
            result.data = data.ToList();

            return result;
        }

        // POST: api/Customer
        public Result Post([FromBody] customerDto value)
        {
            customer cust = new customer();
            cust.CId = value.CId;
            cust.nickname = value.nickname;
            cust.mobilePhone = value.mobilePhone;
            cust.loginPwd = value.loginPwd;
            cust.gender = value.gender;
            cust.birthday = value.birthday;
            cust.address = value.address;
            cust.loginPwd = MD5Helper.Md5(value.loginPwd, "X2");

            bool bol = new customerBll().Add(cust);

            Result result = new Result();
            result.code = bol ? 1 : 0;
            result.msg = bol ? "顾客信息添加成功！" : "error";
            return result;
        }

        // PUT: api/Customer/5
        public Result Put([FromBody] customerDto value)
        {
            //value.LoginPwd = MD5Helper.Md5(value.LoginPwd, "X2");

            customer user = new customer();
            user.CId = value.CId;
            user.nickname = value.nickname;
            user.mobilePhone = value.mobilePhone;
            user.birthday = value.birthday;
            user.gender = value.gender;
            user.loginPwd = value.loginPwd;
            user.address = value.address;

            bool bol = new customerBll().UpdateCust(user);

            Result result = new Result();
            result.code = bol ? 1 : 0;
            result.msg = bol ? "顾客信息修改成功！" : "出错了！";
            return result;
        }

        // DELETE: api/Customer/5
        public Result Delete(int id)
        {
            bool bol = new customerBll().DeleteCust(id);

            Result result = new Result();
            result.code = bol ? 1 : 0;
            result.msg = bol ? "顾客信息删除成功！" : "出错了！";
            return result;
        }

        [HttpDelete]
        public Result Delete([FromBody] int[] value)
        {
            bool bol = new customerBll().DeleteCust(value);

            Result result = new Result();
            result.code = bol ? 1 : 0;
            result.msg = bol ? "顾客信息删除成功！" : "出错了！";
            return result;
        }
    }
}
